<template>
  <div>
    <customDialog
      :title="`${title}用户${titleName}`"
      :dialogVisible="dialogVisible"
      @close="closeDialog(ruleFormRef)"
      @confirm="confirmDialog(ruleFormRef)"
      :confirmText="confirmText"
      :confirmAbled="confirmAbled"
      width="650"
    >
      <!--  -->
      <div>
        <el-form
          ref="ruleFormRef"
          :model="formData"
          :rules="rules"
          label-position="left"
          label-width="55px"
          class="form_box"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="昵称" prop="name">
                <el-input
                  v-model="formData.name"
                  placeholder="请输入昵称"
                  maxlength="12"
                  show-word-limit
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="账号" prop="userName">
                <el-input
                  v-model="formData.userName"
                  placeholder="请输入账号，建议使用手机号码"
                  clearable
                  maxlength="20"
                  show-word-limit
                  v-if="title === '新增'"
                />
                <span v-else style="font-size: 16px; color: #333">
                  {{ formData.userName }}
                </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="title === '新增'">
            <el-col :span="24">
              <el-form-item label="密码" prop="password" class="password_box">
                <el-input
                  v-model="formData.password"
                  placeholder="请输入不低于8位字符的密码"
                  clearable
                  type="password"
                  maxlength="16"
                  show-password
                />
                <span v-if="formData?.password" class="limit">
                  {{ `${formData.password.length} / 16` }}
                </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="角色" prop="roleIds">
                <el-select
                  v-model="formData.roleIds"
                  multiple
                  placeholder="请选择角色"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in rolesOption"
                    :key="index"
                    :label="item?.name"
                    :value="item?.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="title === '新增'">
            <el-col :span="24">
              <el-form-item label="状态">
                <el-switch
                  v-model="formData.enabled"
                  style="

--el-switch-on-color: #13ce66"
                  inline-prompt
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </customDialog>

    <!-- 切换小程序 -->
    <appsDialog ref="appsRef" :btnText="'分配'" v-if="appLength" />
  </div>
</template>

<script lang="ts" setup>
import appsDialog from "@/components/AppsDialog/index.vue";
import customDialog from "@/components/CustomDialog/index.vue";
import {
  getRoles,
  addUser,
  updateUser,
  getUserInfo,
} from "@/api/userManage/index";
import type { FormInstance } from "element-plus";
import { useUserStore } from "@/store/modules/user";
import { cloneDeep } from "lodash-es";

const userStore = useUserStore();
const appLength = userStore.user.userApps.length; // 登录用户的小程序数
const appsRef = ref();

const ruleFormRef = ref<FormInstance>();
const dialogVisible = ref(false);
const confirmAbled = ref(true);
const confirmText = ref<string>("");

const form = {
  id: 0,
  name: "",
  userName: "",
  roleIds: [],
  password: "",
  enabled: true,
  orgId: 0,
  orgIds: [],
};
const formData = ref(Object.assign({}, form));

const title = ref<string>("");
const titleName = ref<string>("");
const rolesOption = ref<Array<any>>([]); // 剧集

watch(
  () => formData.value,
  (item: Record<string, any>) => {
    if (
      item.name &&
      item.userName &&
      item.password &&
      item.roleIds.length &&
      title.value == "新增"
    ) {
      confirmAbled.value = false;
    }
  },
  { deep: true }
);

const validataPass = (rule: any, value: any, callback: any) => {
  // 匹配包含数字、字母或者字符的8-16位正则表达式
  let reg = /^[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,16}$/;
  if (!reg.test(value)) {
    callback(
      new Error("密码长度为8-16个字符，由大小写字母、数字或标点符号组成")
    );
  } else {
    callback();
  }
};
const rules = reactive({
  name: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  userName: [
    {
      required: true,
      message: "请输入账号，建议使用手机号码",
      trigger: "blur",
    },
  ],
  roleIds: [{ required: true, message: "请选择角色", trigger: "change" }],
  password: [{ required: true, validator: validataPass, trigger: "blur" }],
});

// 关闭
const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl?.resetFields();
  Object.assign(formData.value, form);
  dialogVisible.value = false;
};

// 成功
const emit = defineEmits(["success"]);
const confirmDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      let URL;
      if (title.value == "编辑") {
        URL = updateUser;
      } else {
        URL = addUser;
      }

      URL(formData.value).then((res: Record<string, any>) => {
        // ElMessage.success(`${title.value}成功`);
        dialogVisible.value = false;
        emit("success");

        // 下一步选择用户小程序
        let tmp = { ...formData.value, useId: res.data };
        appsRef.value.showDialog(tmp);

        closeDialog(ruleFormRef.value);
      });
    }
  });
};

const getInfo = (val: Record<string, any>) => {
  getUserInfo({ id: val.id }).then((res: Record<string, any>) => {
    formData.value.id = val.id;
    formData.value.name = val.name;
    formData.value.userName = val.userName;
    formData.value.roleIds = res.data.roleIds;
    formData.value.enabled = val.enabled;
    formData.value.orgId = 0;
    formData.value.orgIds = [];
    titleName.value = `-${formData.value.name}`;
  });
};

// 获取角色
const getRolesList = () => {
  getRoles({}).then((res: Record<string, any>) => {
    rolesOption.value = res.data.filter((item: Record<string, any>) => {
      if (item.type == 2) return item;
    });
  });
};

// 父级电子显示dialog
const showDialog = async (val: any) => {
  // console.log("显示弹窗----", val);
  dialogVisible.value = true;
  title.value = val ? "编辑" : "新增";
  confirmText.value = title.value == "新增" ? "下一步" : "确定";
  confirmAbled.value = title.value == "新增" ? true : false;
  getRolesList();
  if (val) {
    getInfo(val);
  }
};

defineExpose({
  showDialog,
});
</script>

<style scoped lang="scss">
.form_box {
  padding: 0 20px;

  .password_box {
    position: relative;

    .limit {
      position: absolute;
      right: 11px;
      font-size: 12px;
      color: #909399;
    }

    :deep(.el-input__wrapper) {
      padding-right: 54px;
    }
  }
}
</style>
